<?php  defined('BASEPATH') OR exit('No direct script access allowed');

class Articles extends Admin_Controller {

	private $_validation_rules = array(
		array(
				'field'	=> 'category_id',
				'label'	=> 'lang:articles.category_id',
				'rules'	=> 'required|is_natural_no_zero'
		),
		array(
				'field'	=> 'status',
				'label'	=> 'lang:articles.status',
				'rules'	=> 'required|numeric'
		),
		array(
				'field'	=> 'sort',
				'label'	=> 'lang:articles.sort',
				'rules'	=> 'optional'
		)
	);
	public function __construct()
	{
		parent::__construct();
		$this->lang->load('articles/articles');
		$this->load->model('articles/articles_model', 'articles_m');
		$this->load->model('categories/categories_model', 'categories_m');
		$this->load->library('form_validation');
		$supported_languages = $this->config->item('supported_languages');
		foreach($supported_languages as $language => $lang_content){
			if(CURRENT_LANGUAGE == $language){
				$rules = 'required';
			}else{
				$rules = 'optional';
			}
			$this->_validation_rules[] = array(
					'field'	=> 'name_'. $language,
					'label'	=> 'lang:articles.name_label',
					'rules'	=> $rules. '|max_length[100]|trim'
			);
			$this->_validation_rules[] = array(
					'field'	=> 'content_'. $language,
					'label'	=> 'lang:articles.content',
					'rules'	=> $rules. '|max_length[2000]'
			);
		}
		$this->form_validation->set_rules($this->_validation_rules);
		array_unshift($this->shortcuts, array('name' => lang('menu_2_catalog_articles'), 'link' => site_url('admin/catalog/articles')),
				array('name' => lang('menu_2_catalog_create_article'), 'link' => site_url('admin/catalog/create_article')));
		array_unshift($this->shortcuts, array('name' => lang('menu_2_catalog_categories'), 'link' => site_url('admin/catalog/categories')),
				array('name' => lang('menu_2_catalog_create_category'), 'link' => site_url('admin/catalog/create_category')));
		$this->template->set_data('shortcuts', $this->shortcuts);
		$categories = $this->categories_m->get_lang_list(FALSE, CURRENT_LANGUAGE);
		$this->template->set_data('categories', $categories);
	}

	// ------------------------------------------------------------------------

	public function index()
	{
		$pagination = create_pagination('admin/catalog/articles' , $this->articles_m->count_lang_list(FALSE, CURRENT_LANGUAGE), 15, 4);
		$articles = $this->articles_m->get_lang_list(array('offset' =>$pagination['limit'][1], 'limit' => $pagination['limit'][0], 'order_by' => 'created DESC'), CURRENT_LANGUAGE);
		$this->template->load('articles/list', array(
			'pagination' => $pagination,
			'articles' => $articles
		));
	}
	
	public function search()
	{
		$active = $this->input->post('active');
		$category = $this->input->post('category');
		$keyword = $this->input->post('keyword');
	
		$url_active = substr($this->uri->segment(4, 'active_'), 7);
		$url_category = substr($this->uri->segment(5, 'category_'), 9);
		$url_keyword = url_base64_decode(substr($this->uri->segment(6, 'keyword_'), 8));
	
		$keyword = $keyword === FALSE? $url_keyword: $keyword;
		$active = $active === FALSE? $url_active: $active;
		$category = $category === FALSE? $url_category: $category;
	
		$where = array();
		if('all' != $active){
			$where['status'] = $active;
		}
		if(!empty($category)){
			$where['category_id'] = $category;
		}
		if(FALSE != $keyword && "" != trim($keyword)){
			$where['like'] = array('name' => trim($keyword));
		}
		
		$pagination = create_pagination(
				'admin/catalog/search_articles/active_' . $active. '/category_'. $category . '/keyword_'. url_base64_encode($keyword) , $this->articles_m->count_lang_list($where, CURRENT_LANGUAGE), 15, 7);
		$articles = $this->articles_m->get_lang_list($where + array('offset' =>$pagination['limit'][1], 'limit' => $pagination['limit'][0]), CURRENT_LANGUAGE);
		$this->template->load('articles/search', array(
				'articles' => $articles,
				'keyword' => $keyword,
				'category' => $category,
				'pagination' => $pagination,
				'active' => $active
		));
	}

	// ------------------------------------------------------------------------

	/**
	 * Checks if the element save process can be done.
	 *
	 * @returns		Boolean		True if the save can be done, false if not
	 *
	 */
	function _check_before_save()
	{
		$default_lang = Settings_lib::get('site_lang');
		$default_lang_name = $this->input->post('name_'.$default_lang);
	
		if ($default_lang_name == FALSE)
		{
			return FALSE;
		}
	
		return TRUE;
	}
	
	// ------------------------------------------------------------------------
	
	public function create()
	{
		if ($this->form_validation->run())
		{
			if ($this->_check_before_save() == TRUE)
			{
				list($data, $lang_data) = $this->_prepare_data($this->articles_m->get_table());
				$data['created'] = $data['updated'] = time();
				$article_id = $this->articles_m->save($data, $lang_data);
				
				if($article_id){
					$message	= lang('articles.create_success');
					$status		= 'success';
				}else{
					$message	= lang('articles.create_error');
					$status		= 'error';
				}
				$this->session->set_flashdata($status, $message);
				redirect('admin/catalog/articles');
			}
		}

		foreach ($this->_validation_rules as $rules)
		{
			$article->{$rules['field']} = set_value($rules['field']);
		}
		$this->load->model('regions/regions_model', 'regions_m');
		$this->data['cities'] = $this->regions_m->get_lang_list(array('region_type' => 3), CURRENT_LANGUAGE);
		$this->data['article'] = $article;
		$this->template->set('site_title', lang('articles.create_title'))->load('articles/create', $this->data);
	}

	// ------------------------------------------------------------------------

	public function edit($id = 0)
	{
		$article = $this->articles_m->get($id);
		
		if ( ! $article)
		{
			redirect('admin/catalog/articles');
		}
		$article_lang = $this->articles_m->get_lang(array('id' => $id));
		$article->langs = fetch_lang($article_lang);
		
		if ($this->form_validation->run())
		{
			if ($this->_check_before_save() == TRUE)
			{
				list($data, $lang_data) = $this->_prepare_data($this->articles_m->get_table());
				$data['updated'] = time();
				$article_id = $this->articles_m->save($data, $lang_data);
	
				if($article_id){
					$message	= lang('articles.create_success');
					$status		= 'success';
				}else{
					$message	= lang('articles.create_error');
					$status		= 'error';
				}
			}
			$this->session->set_flashdata($status, $message);
			redirect('admin/catalog/articles');
		}
		$this->load->model('regions/regions_model', 'regions_m');
		$this->data['cities'] = $this->regions_m->get_lang_list(array('region_type' => 3), CURRENT_LANGUAGE);
		$this->data['article'] = $article;
// 		p($article);
		$this->template->set('site_title', sprintf(lang('articles.edit_title'), def_lang($article, 'name')))->load('articles/edit', $this->data);
	}

	// ------------------------------------------------------------------------

	public function delete($id = 0)
	{
		$ids = $id
			? is_array($id)
				? $id
				: array($id)
			: (array) $this->input->post('action_to');

		$total		= sizeof($ids);
		$deleted	= array();

		// Try do deletion
		foreach ($ids as $id)
		{
			// Get the row to use a value.. as title, name
			if ($article = $this->articles_m->_get($id, CURRENT_LANGUAGE))
			{
				// Make deletion retrieving an status and store an value to display in the messages
				$deleted[($this->articles_m->delete($id) ? 'success': 'error')][] = $article->name;
			}
		}

		// Set status messages
		foreach ($deleted as $status => &$values)
		{
			// Mass deletion
			if (($status_total = sizeof($values)) > 1)
			{
				$last_value		= array_pop($values);
				$first_values	= implode(', ', $values);

				// Success / Error message
				$values = sprintf(lang('articles.delete_mass_' . $status), $status_total, $total, $first_values, $last_value);
			}

			// Single deletion
			else
			{
				// Success / Error messages
				$values = sprintf(lang('articles.delete_' . $status), $values[0]);
			}
		}

		// He arrived here but it was not done nothing, certainly valid ids not were selected
		if ( ! $deleted)
		{
			$status		= 'error';
			$deleted	= array('error' => lang('articles.no_select_error'));
		}
		else
		{
			$status = array_key_exists('error', $deleted) ? 'error': 'success';
		}

		foreach ($deleted as $status => $message)
		{
			$this->session->set_flashdata($status, $message);
		}

		redirect('admin/catalog/articles');
	}
	
	public function activate()
	{
		if ( ! ($ids = $this->input->post('action_to')))
		{
			$this->session->set_flashdata('error', $this->lang->line('articles.activate_error'));
			redirect('admin/catalog/articles');
		}
	
		$activated = 0;
		$to_activate = 0;
		foreach ($ids as $id)
		{
			if ($this->articles_m->update($id, array('status' => 1), TRUE))
			{
				$activated++;
			}
			$to_activate++;
		}
		$this->session->set_flashdata('success', sprintf($this->lang->line('articles.activate_success'), $activated, $to_activate));
	
		redirect('admin/catalog/articles');
	}
	public function deactivate()
	{
		// Activate multiple
		if ( ! ($ids = $this->input->post('action_to')))
		{
			$this->session->set_flashdata('error', $this->lang->line('articles.activate_error'));
			redirect('admin/catalog/articles');
		}
	
		$activated = 0;
		$to_activate = 0;
		foreach ($ids as $id)
		{
			if ($this->articles_m->update($id, array('status' => 0), TRUE))
			{
				$activated++;
			}
			$to_activate++;
		}
		$this->session->set_flashdata('success', sprintf($this->lang->line('articles.deactivate_success'), $activated, $to_activate));
	
		redirect('admin/catalog/articles');
	}

	// ------------------------------------------------------------------------

	public function action()
	{
		$action = strtolower($this->input->post('btnAction'));
		
		if ($action)
		{
			// Get the id('s)
			$id_array = $this->input->post('action_to');

			// Call the action we want to do
			if (method_exists($this, $action))
			{
				return $this->{$action}($id_array);
			}
		}

		redirect('admin/catalog/articles');
	}
}
